package dao

import (
	"bookmark-web/models"
	"errors"
	"strconv"
)

// CreateUser 创建用户
func CreateUser(user *models.User) error {
	// INSERT INTO users (username, password, email, created_at, updated_at) VALUES (?, ?, ?, NOW(), NOW())
	result := DB.Create(user)
	return result.Error
}

// GetUserByUsername 根据用户名获取用户
func GetUserByUsername(username string) (*models.User, error) {
	var user models.User
	// SELECT * FROM users WHERE username = ? LIMIT 1
	result := DB.Where("username = ?", username).First(&user)
	if result.Error != nil {
		// 用户不存在，返回错误信息
		return nil, result.Error
	}
	// 存在，返回用户信息
	return &user, nil
}

// GetUserByEmail 根据邮箱获取用户
func GetUserByEmail(email string) (*models.User, error) {
	var user models.User
	// SELECT * FROM users WHERE email = ? LIMIT 1
	result := DB.Where("email = ?", email).First(&user)
	if result.Error != nil {
		return nil, result.Error
	}
	return &user, nil
}

// GetUserByID 根据ID获取用户
func GetUserByID(id string) (*models.User, error) {
	var user models.User
	// SELECT * FROM users WHERE id = ? LIMIT 1
	result := DB.Where("id = ?", id).First(&user)
	if result.Error != nil {
		return nil, result.Error
	}
	return &user, nil
}

// CheckUserExists 检查用户名或邮箱是否已存在
func CheckUserExists(username, email string) error {
	var count int64

	if username != "" {
		// SELECT count(*) FROM users WHERE username = ?
		DB.Model(&models.User{}).Where("username = ?", username).Count(&count)
		if count > 0 {
			return errors.New("用户名已存在")
		}
	} else {
		// SELECT count(*) FROM users WHERE email = ?
		DB.Model(&models.User{}).Where("email = ?", email).Count(&count)
		if count > 0 {
			return errors.New("邮箱已存在")
		}
	}

	return nil
}

// GetAllUsers 获取所有用户（可用于测试）
func GetAllUsers() ([]models.User, error) {
	var users []models.User
	// SELECT * FROM users
	result := DB.Find(&users)
	return users, result.Error
}

// UpdateUserById 动态更新用户信息
func UpdateUserById(id string, user models.User) error {
	// 构建 sql 语句
	updates := map[string]interface{}{}
	if user.Username != "" {
		updates["username"] = user.Username
	}
	if user.Email != "" {
		updates["email"] = user.Email
	}
	if user.Password != "" {
		updates["password"] = user.Password
	}
	// 如果没有任何字段需要更新，则返回
	if len(updates) == 0 {
		return nil
	}
	result := DB.Model(&models.User{}).Where("id = ?", id).Updates(updates)
	return result.Error
}

// DeleteUserById 删除用户并级联删除其分类和书签
func DeleteUserById(id string) error {
	// 先将 string id 转换为 uint
	userID, err := strconv.ParseUint(id, 10, 32)
	if err != nil {
		return err
	}
	uintUserID := uint(userID)

	// 开始事务
	tx := DB.Begin()
	defer func() {
		if r := recover(); r != nil {
			tx.Rollback()
			panic(r)
		}
	}()

	// 1. 删除用户所有书签
	if err := tx.Where("user_id = ?", uintUserID).Delete(&models.Bookmark{}).Error; err != nil {
		tx.Rollback()
		return err
	}

	// 2. 删除用户所有分类
	if err := tx.Where("user_id = ?", uintUserID).Delete(&models.Category{}).Error; err != nil {
		tx.Rollback()
		return err
	}

	// 3. 删除用户本身
	if err := tx.Where("id = ?", id).Delete(&models.User{}).Error; err != nil {
		tx.Rollback()
		return err
	}

	// 提交事务
	return tx.Commit().Error
}
